package com.firewolf.rbac.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 作者：刘兴
 * 时间:19/3/5
 **/
@RestController
@Slf4j
public class RestLoginController {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @GetMapping("/hello")
    public String hello() {
        log.error("hello");
        return "hello,world";
    }

    @GetMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        redirectStrategy.sendRedirect(request, response, "/login.html");
    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/admin")
    public String admin() {
        return "you are a admin";
    }

    @PreAuthorize("hasRole('ROLE_USER')")
    @GetMapping("/user")
    public String user() {
        return "you are a normal user";
    }

    @GetMapping("/info")
    public Object userinfo() {
        return SecurityContextHolder.getContext().getAuthentication().getDetails();
    }
}
